package main

import (
	"errors"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"time"
)

// 1. 结构体定义
type Person struct {
	Name    string
	Age     int
	Address Address
}

type Address struct {
	City    string
	ZipCode string
}

// 2. 接口定义
type Speaker interface {
	Speak() string
}

// 3. 为结构体实现接口
func (p Person) Speak() string {
	return fmt.Sprintf("Hello, I'm %s, %d years old", p.Name, p.Age)
}

// 4. 方法定义
func (p *Person) Birthday() {
	p.Age++
	fmt.Printf("Happy birthday %s! Now you are %d\n", p.Name, p.Age)
}

// 5. 函数定义（多返回值）
func Divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

// 6. 变参函数
func CalculateSum(numbers ...int) int {
	sum := 0
	for _, num := range numbers {
		sum += num
	}
	return sum
}

// 7. 闭包示例
func Counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func main() {
	// 8. 变量声明和初始化
	var message string = "Go Language Demo"
	shortMessage := "Short declaration"
	fmt.Println(message, shortMessage)

	// 9. 基本数据类型
	var (
		integer  int     = 42
		floatNum float64 = 3.14159
		boolean  bool    = true
		char     rune    = 'A'
	)
	fmt.Printf("Integer: %d, Float: %.2f, Boolean: %t, Char: %c\n",
		integer, floatNum, boolean, char)

	// 10. 数组和切片
	var arr [3]int = [3]int{1, 2, 3}
	slice := []int{4, 5, 6, 7, 8}
	slice = append(slice, 9) // 切片追加

	// 11. 映射（Map）
	ages := map[string]int{
		"Alice": 25,
		"Bob":   30,
	}
	ages["Charlie"] = 28

	// 12. 控制结构
	// if-else
	if value, exists := ages["Alice"]; exists {
		fmt.Printf("Alice is %d years old\n", value)
	}

	// switch
	switch day := time.Now().Weekday(); day {
	case time.Saturday, time.Sunday:
		fmt.Println("It's weekend!")
	default:
		fmt.Println("It's weekday")
	}

	// 13. 循环
	// for 循环
	fmt.Print("Array elements: ")
	for i := 0; i < len(arr); i++ {
		fmt.Printf("%d ", arr[i])
	}
	fmt.Println()

	// range 循环
	fmt.Print("Slice elements: ")
	for index, value := range slice {
		fmt.Printf("[%d]=%d ", index, value)
	}
	fmt.Println()

	fmt.Print("Map contents: ")
	for key, value := range ages {
		fmt.Printf("%s:%d ", key, value)
	}
	fmt.Println()

	// 14. 结构体使用
	person := Person{
		Name: "John Doe",
		Age:  25,
		Address: Address{
			City:    "New York",
			ZipCode: "10001",
		},
	}

	// 15. 接口使用
	var speaker Speaker = person
	fmt.Println(speaker.Speak())

	// 16. 方法调用
	person.Birthday()

	// 17. 错误处理
	result, err := Divide(10, 2)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("10 / 2 = %.2f\n", result)

	// 18. 变参函数调用
	sum := CalculateSum(1, 2, 3, 4, 5)
	fmt.Printf("Sum: %d\n", sum)

	// 19. 闭包使用
	counter := Counter()
	fmt.Printf("Counter: %d, %d, %d\n", counter(), counter(), counter())

	// 20. 指针操作
	pointerDemo(&person)

	// 21. 类型断言
	interfaceDemo(person)

	// 22. defer 语句
	deferDemo()

	// 23. goroutine 和 channel
	concurrencyDemo()

	// 24. 文件操作
	fileDemo()

	// 25. 字符串操作
	stringDemo()
}

// 指针示例
func pointerDemo(p *Person) {
	fmt.Printf("Original age: %d\n", p.Age)
	p.Age += 5
	fmt.Printf("After pointer modification: %d\n", p.Age)
}

// 接口类型断言示例
func interfaceDemo(s Speaker) {
	// 类型断言
	if person, ok := s.(Person); ok {
		fmt.Printf("Type assertion successful: %s\n", person.Name)
	}

	// 类型switch
	switch v := s.(type) {
	case Person:
		fmt.Printf("It's a Person: %s\n", v.Name)
	default:
		fmt.Printf("Unknown type: %T\n", v)
	}
}

// defer 示例
func deferDemo() {
	fmt.Println("Start of function")
	defer fmt.Println("This is deferred 1")
	defer fmt.Println("This is deferred 2")
	fmt.Println("End of function")
}

// 并发示例
func concurrencyDemo() {
	// 创建channel
	ch := make(chan string, 2)

	// goroutine
	go func() {
		time.Sleep(1 * time.Second)
		ch <- "Hello from goroutine"
		ch <- "Second message"
		close(ch)
	}()

	// 从channel接收
	fmt.Println("Waiting for messages...")
	for msg := range ch {
		fmt.Printf("Received: %s\n", msg)
	}
}

// 文件操作示例
func fileDemo() {
	// 写入文件
	filename := "demo.txt"
	err := os.WriteFile(filename, []byte("Hello, Go!\nThis is a demo file."), 0644)
	if err != nil {
		log.Printf("File write error: %v", err)
		return
	}

	// 读取文件
	data, err := os.ReadFile(filename)
	if err != nil {
		log.Printf("File read error: %v", err)
		return
	}
	fmt.Printf("File content: %s\n", string(data))

	// 清理
	os.Remove(filename)
}

// 字符串操作示例
func stringDemo() {
	str := "Hello, 世界" // Unicode 支持

	// 字符串遍历
	fmt.Print("String runes: ")
	for i, r := range str {
		fmt.Printf("[%d:%c] ", i, r)
	}
	fmt.Println()

	// 字符串转换
	numStr := "123"
	if num, err := strconv.Atoi(numStr); err == nil {
		fmt.Printf("String to int: %d\n", num)
	}

	// 字符串格式化
	formatted := fmt.Sprintf("Formatted: %.2f", math.Pi)
	fmt.Println(formatted)
}
